<template>
  <div class="mapBottomBox">
    <div v-show="tableShow" :class="{'zhankai':showType==true}" class="mapBottomDiv" ref="BoxTableParentRef">
      <div class="leftTreeTitle">
        <div>
          <img src="../icon/open.png" alt="" :class="[showType ? 'active' : '']" @click="openTable">
          项目列表
        </div>
        <a-tooltip placement="top">
          <template slot="title">
            <span>隐藏项目列表</span>
          </template>
          <div style="padding-right: 10px;cursor: pointer;" @click="tableShow = false">
            <a-icon type="minus"/>
          </div>
        </a-tooltip>
      </div>
      <div class="mapBottomTableBox" ref="BoxTableRef">
        <a-table ref="projectTable"
                 rowKey="id"
                 :columns="columns"
                 :dataSource="projectData"
                 :loading="loading"
                 style="height: 100%;"
                 :row-selection="rowSelection"
                 :customRow="rowclick"
                 :scroll="scrollY"
                 :pagination="false">
        </a-table>
      </div>
    </div>
    <!-- 关闭按钮 -->
    <a-tooltip placement="top">
      <template slot="title">
        <span>显示项目列表</span>
      </template>
      <div class="closeBtn" @click="tableShow = true" v-show="!tableShow">
        <a-icon type="menu-unfold" style="font-size: 1.5em; color: #000"/>
      </div>
    </a-tooltip>

    <div class="projectDetail" v-if="projectDetailShow">
      <div class="leftTreeTitle">
        <div>
          <a-icon type="menu-unfold" style="color: #fff"/>
          项目详情
        </div>
        <a-tooltip placement="top">
          <template slot="title">
            <span>隐藏项目详情</span>
          </template>
          <div style="padding-right: 10px;cursor: pointer;" @click="projectDetailShow = false">
            <a-icon type="minus"/>
          </div>
        </a-tooltip>
      </div>
      <div class="property-details">
        <table>
          <tbody>
          <tr>
            <td>项目名称：</td>
            <td><span>{{ selectProject.projectName }}</span></td>
          </tr>
          <tr>
            <td>建设地点：</td>
            <td><span>{{ selectProject.jsddContent }}</span></td>
          </tr>
          <tr>
            <td>建设时间：</td>
            <td><span>{{ selectProject.projectStartYear }}</span></td>
          </tr>
          <!--          <tr>-->
          <!--            <td>项目类型：</td>-->
          <!--            <td><span>{{ selectProject.projectType }}</span></td>-->
          <!--          </tr>-->
          <!--          <tr>-->
          <!--            <td>项目状态：</td>-->
          <!--            <td><span>{{ selectProject.projectStatus }}</span></td>-->
          <!--          </tr>-->
          </tbody>
        </table>
      </div>
    </div>

  </div>
</template>

<script>
import * as turf from "@turf/turf";
import MapUtils from "../js/mapUtil/MapUtils";
import Bus from "@/utils/bus";
import {Stroke, Style, RegularShape} from 'ol/style';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import {fromLonLat} from "ol/proj";

export default {
  name: "MapBottomTable",
  data() {
    return {
      shipCheckBoxSource: null,
      shipCheckBoxLayer: null,
      shipCheckBoxFeature: null,
      shipCheckBoxId: "select_check_box",
      showType: false,
      tableShow: true,
      projectDetailShow: false,
      selectProject: {},
      scrollY: {y: 240 - 54},
      loading: false,
      selectId: [],
      rowSelection: {
        hideSelectAll: true,
        type: 'radio',
        selectedRowKeys: [],
        onChange(selectedRowKey) {
          this.selectedRowKeys = selectedRowKey
        },
      },
      projectData: [],
      columns: [
        {
          title: '项目名称',
          dataIndex: 'projectName',
          key: 'projectName',
          width: 150,
          scopedSlots: {customRender: 'projectName'},
        },
        {
          title: '建设地点',
          dataIndex: 'jsddContent',
          key: 'jsddContent',
          width: 150,
          scopedSlots: {customRender: 'jsddContent'},
        },
        {
          title: '建设时间',
          dataIndex: 'projectStartYear',
          key: 'projectStartYear',
          width: 100,
          scopedSlots: {customRender: 'projectStartYear'},
        },
      ],
    };
  },
  methods: {
    openTable() {
      this.showType = !this.showType
      //获取this.$refs.BoxTableRef的高度
      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollY = {y: this.$refs.BoxTableParentRef.clientHeight - 40 - 54}
        }, 500)
      })
    },
    windowResize() {
      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollY = {y: this.$refs.BoxTableParentRef.clientHeight - 40 - 54}
        }, 10)
      })
    },
    // 项目列表
    getProjectList() {
      // this.loading = true;
      // this.$api.project.getProjectList().then(res => {
      this.loading = false;
      // if (res.code === 200) {
      // this.projectData = res.data;
      // }
      // });
    },
    initProjectData() {
      this.projectData = []
      for (let i = 0; i < 100; i++) {
        //随机一个经纬度坐标，保留6位小数
        let point = turf.randomPosition([121, 22, 82, 45])
        this.projectData.push({
          id: i,
          projectName: '项目名称' + i,
          jsddContent: '建设地点' + i,
          projectStartYear: '建设时间' + i,
          longitude: point[0],
          latitude: point[1],
          imgIcon: require("../icon/project.png")//把想显示的图片绑定到单个项目
        })
      }
      //加载到地图上
      this.addProjectToMap();
    },
    addProjectToMap() {
      MapUtils.addProjects(this.projectData)
    },
    scrollToRow(rowindex, isprecise = false) {
      let tableElement = this.$refs.projectTable
      let BoxTable = this.$refs.BoxTableRef
      const theTableRows = tableElement.$el.querySelectorAll('.ant-table-body tbody .ant-table-row')
      let scrollTop = 0;
      for (let i = 0; i < theTableRows.length; i++) {
        if (i === rowindex) {
          break
        }
        scrollTop = theTableRows[i].offsetHeight + scrollTop
        if (!isprecise) {
          scrollTop *= (rowindex - 2);
          break;
        }

      }
      BoxTable.scrollTo(0, scrollTop)
    },
    rowclick(record, index) {
      return {
        on: {
          click: () => {
            this.showSelectProject(record)
            MapUtils.flyTo(record.longitude, record.latitude)
          },
        }
      };
    },
    /**
     * point: [lon, lat]
     * radius: 选中框的半径，即中心点到四个顶点的距离
     */
    drawCheckBoxByRadius(point, radius) {
      let that = this
      let lonlat = fromLonLat([point.longitude, point.latitude]);
      if (!that.shipCheckBoxLayer) {
        that.shipCheckBoxSource = new VectorSource({
          features: [],
        })
        that.shipCheckBoxLayer = new VectorLayer({
          source: that.shipCheckBoxSource,
          zIndex: 100,
        })
        map.addLayer(that.shipCheckBoxLayer)
      }

      // 首先获取选中框
      let CheckBoxFeature = that.shipCheckBoxSource.getFeatureById(that.shipCheckBoxId);
      if (CheckBoxFeature === null) { // 若选中框不存在，开始绘制选中框
        // init选中框的 Layer 和 Source
        that.initShipCheckBoxSource()
        that.shipCheckBoxLayer.setSource(this.shipCheckBoxSource)
        // 根据半径，计算出选中框的边长
        let longRadius = radius * Math.SQRT2;
        let styless = new Style({
          image: new RegularShape({
            stroke: new Stroke({
              color: "#f00",
              width: 0.8,
              // 实虚比例，这里使用3:4:3:0比例，显示效果为  3实线 4透明  3实线  0透明，依次循环，形成一个选中框样式
              lineDash: [longRadius * 3 / 10, longRadius * 4 / 10, longRadius * 3 / 10, 0]
            }),
            radius: radius,
            points: 4,
            // openlayers中，多边形默认角朝上，所以需要将图形翻转45度
            rotation: Math.PI / (180 / 45),
          }),
        })
        let shipFeature = new Feature({
          geometry: new Point(lonlat)
        });
        // 放入id方便随时获取
        shipFeature.setId(that.shipCheckBoxId);
        shipFeature.setStyle(styless)
        that.shipCheckBoxSource.addFeature(shipFeature);
      } else { // 若选中框已存在，重新定位
        CheckBoxFeature.setGeometry(new Point(lonlat));
      }
    },
    initShipCheckBoxSource() {
      this.shipCheckBoxSource = new VectorSource({
        features: [],
      });
    },
    removeCheckBox() {
      let that = this
      if (that.shipCheckBoxSource) {
        let CheckBoxFeature = that.shipCheckBoxSource.getFeatureById(that.shipCheckBoxId);
        if (CheckBoxFeature !== null) {
          that.projectDetailShow = false
          that.shipCheckBoxSource.removeFeature(CheckBoxFeature);
          that.selectProject = null
        }
      }
    },
    showSelectProject(data) {
      this.rowSelection.selectedRowKeys = [data.id]
      //选中效果
      this.drawCheckBoxByRadius(data, 40)
      //显示项目详情
      this.projectDetailShow = true
      this.selectProject = data
    },
  },
  mounted() {
    Bus.$on("mapLoaded", () => {
      this.initProjectData();
      // this.getProjectList();
    })
    Bus.$on('clickFeature', (feature) => {
      if (feature) {
        let data = feature.get("data")
        let index = 0
        for (let i = 0; i < this.projectData.length; i++) {
          if (this.projectData[i].id === data.id) {
            index = i;
            break;
          }
        }
        //列表高亮并定位到项目
        this.scrollToRow(index, true)
        this.showSelectProject(data)
      } else {
        this.removeCheckBox()
        this.rowSelection.selectedRowKeys = []
      }
    })
    Bus.$on('clearProject',()=>{
      MapUtils.removeProject();
      this.removeCheckBox()
      //加载新的project
      this.initProjectData();
    })
    window.onresize = () => {
      this.windowResize()
    }
  },
  destroyed() {
    MapUtils.removeProject();
    this.removeCheckBox()
  },
}
</script>

<style scoped lang="less">
.mapBottomBox {
  .mapBottomDiv {
    position: absolute;
    bottom: 40px;
    left: 250px;
    width: calc(100% - 320px);
    background: #fff;
    height: 300px;
    transition: all 0.5s;

    .leftTreeTitle {
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: bold;
      color: #fff;
      border-bottom: 1px solid #ccc;
      background: #373737;
      padding-left: 10px;
      display: flex;
      justify-content: space-between;

      img {
        width: 20px;
        height: 20px;
        transition: height 0.5s;
        cursor: pointer;
      }

      img.active {
        transform: rotate(180deg);
      }
    }

    .mapBottomTableBox {
      height: calc(100% - 40px);
      overflow: hidden;
    }
  }

  .zhankai {
    height: 80%;
    z-index: 1004;
  }

  .closeBtn {
    position: absolute;
    bottom: 40px;
    left: 250px;
    width: 20px;
    height: 20px;
    cursor: pointer;
  }

  .projectDetail {
    position: absolute;
    width: 300px;
    height: 300px;
    top: 20px;
    right: 20px;
    background: #fff;
    z-index: 100;
    border-radius: 10px;
    box-shadow: #444444 0px 0px 10px;

    .leftTreeTitle {
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: bold;
      color: #fff;
      border-bottom: 1px solid #ccc;
      background: #373737;
      padding-left: 10px;
      display: flex;
      justify-content: space-between;

      img {
        width: 20px;
        height: 20px;
        transition: height 0.5s;
        cursor: pointer;
      }
    }
  }

  .property-details {
    padding: 10px;
    border-radius: 5px;
    font-size: 14px;
  }

  .property-details table {
    width: 100%;
  }

  .property-details td {
    padding: 5px;
  }

  .property-details td span {
    display: inline-block;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .property-details td:first-child {
    font-weight: bold;
  }

}

</style>
